package com.sg.business.commons.labelprovider;

import java.util.List;

import org.bson.types.ObjectId;
import org.eclipse.swt.graphics.Image;

import com.mobnut.db.model.ModelService;
import com.mobnut.db.model.PrimaryObject;
import com.mongodb.DBObject;
import com.sg.business.model.Organization;
import com.sg.widgets.commons.labelprovider.ConfiguratorColumnLabelProvider;

public class OrganizationLabel extends ConfiguratorColumnLabelProvider {

	@Override
	protected Object getValue(Object element) {
		if (element instanceof PrimaryObject) {
			return super.getValue(element);
		} else {
			return element;
		}
	}

	@Override
	public String getText(Object element) {
		return getOrganizationText(element);
	}

	private String getOrganizationText(Object element) {
		String text = null;
		if (element instanceof PrimaryObject) {
			Object value = ((PrimaryObject) element).getValue(getFieldName());
			if (value instanceof ObjectId) {
				Organization org = ModelService.createModelObject(
						Organization.class, (ObjectId) value);
				text = org == null ? "" : org.getLabel();
			} else if (value instanceof List<?>) {
				List<?> list = (List<?>) value;
				text = "";
				for (Object obj : list) {
					text += getOrganizationText(obj) + ",";
				}
			}
		} else if (element instanceof ObjectId) {
			Organization org = ModelService.createModelObject(
					Organization.class, (ObjectId) element);
			text = org == null ? "" : org.getLabel();
		} else if (element instanceof DBObject) {
			Organization org = ModelService.createModelObject(
					(DBObject) element, Organization.class);
			text = org == null ? "" : org.getLabel();
		} else if (element instanceof List<?> && ((List<?>) element).size() > 0) {
			text = getOrganizationText(((List<?>) element).get(0));
		} else if (element instanceof Object[]) {
			text = getOrganizationText(((Object[]) element)[0]);
		}
		return text;
	}

	@Override
	public Image getImage(Object element) {
		Organization org = getOrganization(element);
		return org == null ? null : org.getImage();
	}

	private Organization getOrganization(Object element) {
		if (element instanceof PrimaryObject) {
			Object value = ((PrimaryObject) element).getValue(getFieldName());
			if (value instanceof ObjectId) {
				return ModelService.createModelObject(Organization.class,
						(ObjectId) value);
			}
		} else if (element instanceof ObjectId) {
			return ModelService.createModelObject(Organization.class,
					(ObjectId) element);
		} else if (element instanceof DBObject) {
			return ModelService.createModelObject((DBObject) element,
					Organization.class);
		} else if (element instanceof List<?> && ((List<?>) element).size() > 0) {
			return getOrganization(((List<?>) element).get(0));
		} else if (element instanceof Object[]) {
			return getOrganization(((Object[]) element)[0]);

		}
		return null;
	}
}
